import {
  getExchangeTable,
  editExchangeRecord
} from '../../api/interactive'
import {
  EXCHANGE_LIST,
  EXCHANGE_CURRENT_ROW,
  EXCHANGE_DATA_COUNT,
  EXCHANGE_HISTORY_DATA,
  EXCHANGE_PAGE_SIZE
} from '../motations-type'

export default {
  state: {
    exchangeList: [],
    exchangeDataCount: null,
    exchangePageSize: 20,
    exchangeHistoryData: [],
    row: {
      gname: '',
      code: '',
      ctime: '',
      state: '',
      type: '',
      suname: '',
      tel: ''
    }
  },
  getters: {
    exchangeList: state => state.exchangeList
  },
  mutations: {
    [EXCHANGE_LIST] (state, data) {
      state.exchangeList = data
    },
    [EXCHANGE_CURRENT_ROW] (state, data) {
      state.row = data
    },
    [EXCHANGE_DATA_COUNT] (state, data) {
      state.exchangeDataCount = data
    },
    [EXCHANGE_HISTORY_DATA] (state, data) {
      state.exchangeHistoryData = data
    },
    [EXCHANGE_PAGE_SIZE] (state, data) {
      state.exchangePageSize = data
    }
  },
  actions: {
    async getExchangeList ({ commit, rootState }, playload) {
      let data = {}
      let newData = []
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await getExchangeTable(data)
      resp.data.data.rows.map((item) => {
        newData = [...newData, {
          id: item.id,
          gname: item.gname,
          code: item.code,
          ctime: item.ctime,
          state: item.state,
          type: item.type,
          suname: item.suname,
          tel: item.tel
        }]
      })
      commit(EXCHANGE_LIST, newData)
      commit(EXCHANGE_DATA_COUNT, resp.data.data.total)
      if (newData.length < rootState.exchange.exchangePageSize) {
        commit(EXCHANGE_HISTORY_DATA, newData)
      } else {
        commit(EXCHANGE_HISTORY_DATA, newData.slice(0, rootState.exchange.exchangePageSize))
      }
      return resp
    },
    async editExchangeData ({ commit, rootState }, playload) {
      let data = {}
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await editExchangeRecord(data)
      return resp
    },
    async getExchangeCurrentRow ({ commit, rootState }, row) {
      commit(EXCHANGE_CURRENT_ROW, row)
    },
    async changeExchangePage ({ commit, rootState }, index) {
      let data = rootState.exchange.exchangeList
      let _start = (index - 1) * rootState.exchange.exchangePageSize
      let _end = index * rootState.exchange.exchangePageSize
      commit(EXCHANGE_HISTORY_DATA, data.slice(_start, _end))
    },
    async changeExchangePageSize ({ commit, rootState }, value) {
      commit(EXCHANGE_PAGE_SIZE, value)
    }
  }
}
